package com.yuanyi.controller;

import com.yuanyi.entity.WebConfig;
import com.yuanyi.util.StringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

@RestController
public class WebConfigController {
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString().replaceAll("-","").substring(0,16));
    }

    @GetMapping("/find_config")
    public WebConfig findConfig(String url) throws UnsupportedEncodingException {
        String noncestr= "noncestr="+StringUtil.rstr(16);
        String jsapi_ticket = "jsapi_ticket="+ (String)
                redisTemplate.opsForValue().get("jsapi_ticket");
        String timestamp =  "timestamp="+ ((new Date()).getTime()/1000)+"";
        url = "url="+ URLDecoder.decode(url,"utf-8");
        String[] arrs = {noncestr,jsapi_ticket,timestamp,url};

        Arrays.sort(arrs);

        StringBuilder str = new StringBuilder();
        for (int i = 0; i < arrs.length; i++) {
            str.append(arrs[i]+"&");
        }


        System.out.println(str.substring(0,str.length()-1));
        String signature = StringUtil.sha1( str.substring(0,str.length()-1));


        WebConfig wc = new WebConfig(timestamp,noncestr,signature);
        return wc;
    }
}
